# -*- coding: UTF-8 -*-
__author__ = "lishang"
__date__ = "$2021-7-9 11:05:46$"

import os,re
import multiprocessing,socket,re,time,urllib.parse
import traceback

def application(env,Response):    
    filePath=env['file']
    file =open(filePath,'r',encoding='utf8')
    responseBody = file.read()
     
    status = 'HTTP/1.1 200 OK'
    responseHeaders = [('Server','kpyhs'),('Date','%s'%time.ctime()),('Content-Type',"text/html; charset=utf-8"),('Access-Control-Allow-Origin','*')]
    Response(status,responseHeaders,responseBody)
    pass

class HttpServer(object):
    application=application
    root="./html/"
    def __init__(self,port=8066,root=""):
        serveSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serveSocket = serveSocket
        self.bind(port)
        if root: 
            self.root=root
            
    def __del__(self):
        self.serveSocket.close()

    def bind(self,port):
        print("bind:%s"%port)
        self.serveSocket.bind(('0.0.0.0',port))

    def start(self):
        self.serveSocket.listen()
        while True:
            clientSocket, clientAddr = self.serveSocket.accept()
            multiprocessing.Process(target=self.serveHandler, args=(clientSocket, clientAddr)).start()
            clientSocket.close()

    def serveHandler(self,clientSocket,clientAddr):
        try:
            recvData = clientSocket.recv(1024).decode('utf8')
            url = re.split(r' +', recvData.splitlines()[0])[1]
            print(url)
            uParse = urllib.parse.urlparse(url)
            fileName=uParse.path
            filePath = self.root+fileName
            request=dict(urllib.parse.parse_qsl(uParse.query) )
            try:
                file=None
                env={'file':filePath,'uri':fileName,'params':request}
                self.application(env,self.Response)
            except FileNotFoundError:
                self.Response( 'HTTP/1.1 404 NOT FOUND',{}, '很抱歉，服务器中找不到你想要的内容')
            finally:
                if (file!=None) and (not file.closed):
                    file.close()

        except Exception as ex:
            responseHeader = 'Server: PyParse_' + os.linesep
            responseHeader += 'Date: %s' % time.ctime()
            self.Response( 'HTTP/1.1 500 ERROR',{}, '服务器正在维护中，请稍后再试。%s'%ex)
            traceback.print_exc()
        finally:
            self.responseHeader+="Content-Length: %s" % len(self.responseBody.encode())
            senData = self.responseLine + os.linesep + self.responseHeader + os.linesep + os.linesep + self.responseBody
            #print(senData)
            senData = senData.encode('utf8')
            clientSocket.send(senData)
            if (clientSocket!=None) and ( not clientSocket._closed):
                clientSocket.close()

    def Response(self,status,responseHeaders,responseBody):
        self.responseLine = status
        self.responseHeader = ''
        if len(responseHeaders)==0: 
            responseHeaders = [('Server', 'PyParse' ),
                                                 ('Date',time.ctime()),
                                                 ('Content-Type',"text/html; charset=utf-8"),
            ];
        for k,v in responseHeaders:
            kv = k + ':' + v + os.linesep
            self.responseHeader += kv
        self.responseBody=responseBody